# -*- coding: utf-8 -*-
# @Time: 2025/5/23 16:55
# @Author: wzd
# @Email: 2146333089@qq.com
# @File: serializers.py
import uuid
from rest_framework import serializers
from .models import Admin, Student, Teacher, School
from .validators import (
    validate_username, validate_password, validate_email,
    validate_phone, validate_student_id, validate_teacher_id
)

class SchoolSerializer(serializers.ModelSerializer):
    class Meta:
        model = School
        fields = ['school_id', 'name']  # 包含学校ID和名称


class BaseUserSerializer(serializers.Serializer):
    password = serializers.CharField(
        write_only=True,
        validators=[validate_password],
        error_messages={
            'required': '密码不能为空',
            'blank': '密码不能为空'
        }
    )
    name = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '姓名不能超过50个字符'
        },
        help_text="用户姓名（学生/教师必填，管理员可选）"
    )
    email = serializers.EmailField(
        validators=[validate_email],
        error_messages={
            'required': '邮箱不能为空',
            'blank': '邮箱不能为空',
            'invalid': '邮箱格式不正确'
        }
    )
    phone = serializers.CharField(
        max_length=11,
        required=False,
        allow_blank=True,
        validators=[validate_phone]
    )
    class Meta:
        # 指定要包含的所有字段
        fields = '__all__'  # 包含所有字


class AdminSerializer(BaseUserSerializer):
    name = serializers.CharField(
        max_length=50,
        validators=[validate_username],
        error_messages={
            'required': '用户名不能为空',
            'blank': '用户名不能为空'
        }
    )

    class Meta:
        # 指定要包含的所有字段
        model = Admin
        fields = '__all__'  # 包含所有字

    def validate(self, data):
        if Admin.objects.filter(name=data['name']).exists():
            raise serializers.ValidationError({'name': '用户名已存在'})
        if Admin.objects.filter(email=data['email']).exists():
            raise serializers.ValidationError({'email': '邮箱已被注册'})
        return data


class StudentSerializer(BaseUserSerializer):
    student_id = serializers.CharField(
        max_length=20,
        validators=[validate_student_id],
        error_messages={
            'required': '学号不能为空',
            'blank': '学号不能为空'
        }
    )
    school = SchoolSerializer(read_only=True)
    school_id = serializers.CharField(
        source='school.school_id',  # 关联学校的school_id
        max_length=20,
        required=True,
        error_messages={
            'required': '学校ID不能为空',
            'blank': '学校ID不能为空'
        }
    )
    grade = serializers.CharField(
        max_length=20,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '年级不能超过20个字符'
        }
    )
    major = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '专业不能超过50个字符'
        }
    )
    created_at = serializers.DateTimeField(
        read_only=True,
        format="%Y-%m-%d %H:%M:%S"
    )
    updated_at = serializers.DateTimeField(
        read_only=True,
        format="%Y-%m-%d %H:%M:%S"
    )
    sex = serializers.CharField(
        max_length=10,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '性别不能超过10个字符'
        }
    )

    class Meta:
        model = Student
        # 显式列出所有字段，确保完整性
        fields = [
            'student_id', 'name', 'password', 'email', 'grade', 'sex',
            'major', 'phone', 'school_id', 'created_at', 'updated_at', 'school'
        ]

    def validate(self, data):
        # 验证学校是否存在
        school_id = data.get('school_id')
        if not School.objects.filter(school_id=school_id).exists():
            print(school_id)
            raise serializers.ValidationError({'school_id': '学校不存在'})

        # 验证学号在学校内唯一
        student_id = data.get('student_id')
        if Student.objects.filter(
            student_id=student_id,
            school__school_id=school_id
        ).exists():
            raise serializers.ValidationError({'student_id': '该学校中此学号已存在'})

        # 验证邮箱全局唯一
        email = data.get('email')
        if Student.objects.filter(email=email).exists():
            raise serializers.ValidationError({'email': '邮箱已被注册'})

        return data

class TeacherSerializer(BaseUserSerializer):
    teacher_id = serializers.CharField(
        max_length=20,
        validators=[validate_teacher_id],
        error_messages={
            'required': '教师编号不能为空',
            'blank': '教师编号不能为空'
        }
    )
    school = SchoolSerializer(read_only=True)
    sex = serializers.CharField(
        max_length=10,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '性别不能超过10个字符'
        }
    )
    introduction = serializers.CharField(
        required=False,
        allow_blank=True,
        max_length=None,
        error_messages={
            'max_length': '简介不能超过2000个字符'
        }
    )
    school_id = serializers.CharField(
        source='school.school_id',  # 关联学校的school_id
        max_length=20,
        required=True,
        error_messages={
            'required': '学校ID不能为空',
            'blank': '学校ID不能为空'
        }
    )

    title = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '职称不能超过50个字符'
        }
    )
    department = serializers.CharField(
        max_length=50,
        required=False,
        allow_blank=True,
        error_messages={
            'max_length': '院系名称不能超过50个字符'
        }
    )
    created_at = serializers.DateTimeField(
        read_only=True,
        format="%Y-%m-%d %H:%M:%S"
    )
    updated_at = serializers.DateTimeField(
        read_only=True,
        format="%Y-%m-%d %H:%M:%S"
    )

    class Meta:
        model = Teacher
        # 显式列出所有模型字段
        fields = [
            'teacher_id', 'name', 'password', 'email', 'title', 'sex', 'introduction',
            'department', 'phone', 'school_id', 'created_at', 'updated_at', 'school'
        ]
        # 或者使用fields = '__all__'包含所有字段
        # fields = '__all__'

    def validate(self, data):
        # 处理学校ID验证
        school_id = data.get('school')['school_id']
        if not School.objects.filter(school_id=school_id).exists():
            print(school_id)
            print(data)
            raise serializers.ValidationError({'school_id': '学校不存在'})

        # 处理教师编号唯一性
        teacher_id = data.get('teacher_id')
        if Teacher.objects.filter(
                teacher_id=teacher_id,
                school__school_id=school_id
        ).exists():
            raise serializers.ValidationError({'teacher_id': '该学校中此教师编号已存在'})

        # 处理邮箱唯一性
        email = data.get('email')
        if Teacher.objects.filter(email=email).exists():
            raise serializers.ValidationError({'email': '邮箱已被注册'})

        return data